// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import {postRequest} from "./utils/api";

Vue.prototype.postRequest = postRequest;
// 设置反向代理，前端请求默认发送到 http://47.115.84.0:8443/api
var axios = require('axios');
axios.defaults.baseURL = 'http://localhost:8181/api';
// 全局注册，之后可在其他组件中通过 this.$axios 发送数据
Vue.prototype.$axios = axios;
Vue.prototype.$store = store;
Vue.config.productionTip = false;
axios.defaults.withCredentials = true;
Vue.use(ElementUI);

router.beforeEach((to, from, next) => {
        if(to.path.startsWith('/login')|| store.state.token){
          if(to.path.startsWith('/admin')){
            initAdminMenu(router, store)
          }
          next();
        }else{
          next({
            path: '/login',
            query: {redirect: to.fullPath}
          })
        }
});

const initAdminMenu = (router, store) => {
  // 防止重复触发加载菜单操作
  if (store.state.adminMenus.length > 0) {
    return
  }
  axios.get('/menu').then(resp => {
    if (resp && resp.code === 200) {
      var fmtRoutes = formatRoutes(resp.obj);
      router.addRoutes(fmtRoutes);
      store.commit('initAdminMenu', fmtRoutes)
    }
  })
};

const formatRoutes = (routes) => {
  let fmtRoutes = [];
  routes.forEach(route => {
    if (route.children) {
      route.children = formatRoutes(route.children)
    }
    let fmtRoute = {
      path: route.path,
      //Vue 的异步组件加载机制（也叫懒加载）
      component: resolve => {
        require(['./components/admin/' + route.component + '.vue'], resolve)
      },
      name: route.name,
      nameZh: route.nameZh,
      iconCls: route.iconCls,
      meta: {
        requireAuth: true
      },
      children: route.children
    };
    fmtRoutes.push(fmtRoute)
  });
  return fmtRoutes
};

new Vue({
  el: '#app',
  render: h =>h(App),
  router,
  store,
  components: { App },
  template: '<App/>'
});

